package com.cargohu.aishouyu.system.service.impl;

import com.cargohu.aishouyu.framework.exception.BusinessException;
import com.cargohu.aishouyu.framework.page.OrderByItem;
import com.cargohu.aishouyu.framework.page.Paging;
import com.cargohu.aishouyu.framework.service.impl.BaseServiceImpl;
import com.cargohu.aishouyu.system.dto.SysConfigAddDTO;
import com.cargohu.aishouyu.system.dto.SysConfigUpdateDTO;
import com.cargohu.aishouyu.system.entity.SysConfig;
import com.cargohu.aishouyu.system.mapper.SysConfigMapper;
import com.cargohu.aishouyu.system.query.SysConfigQuery;
import com.cargohu.aishouyu.system.service.SysConfigService;
import com.cargohu.aishouyu.system.vo.SysConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 参数配置表 服务实现类
 *
 * @author yww
 * @since 2023-11-29
 */
@Slf4j
@Service
public class SysConfigServiceImpl extends BaseServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addSysConfig(SysConfigAddDTO sysConfigAddDTO) throws Exception {
        SysConfig sysConfig = new SysConfig();
        BeanUtils.copyProperties(sysConfigAddDTO, sysConfig);
        return save(sysConfig);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateSysConfig(SysConfigUpdateDTO sysConfigUpdateDTO) throws Exception {
        Long configId = sysConfigUpdateDTO.getConfigId();
        SysConfig sysConfig = getById(configId);
        if (sysConfig == null) {
            throw new BusinessException("参数配置表不存在");
        }
        BeanUtils.copyProperties(sysConfigUpdateDTO, sysConfig);
        sysConfig.setUpdateTime(new Date());
        return updateById(sysConfig);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteSysConfig(Long configId) throws Exception {
        return removeById(configId);
    }

    @Override
    public SysConfigVo getSysConfigById(Long configId) throws Exception {
        return sysConfigMapper.getSysConfigById(configId);
    }

    @Override
    public SysConfigVo getSysConfigByKey(String configKey) throws Exception {
        return sysConfigMapper.getSysConfigByKey(configKey);
    }

    @Override
    public Paging<SysConfigVo> getSysConfigList(SysConfigQuery sysConfigQuery) throws Exception {
        handlePage(sysConfigQuery, OrderByItem.desc("config_id"));
        List<SysConfigVo> list = sysConfigMapper.getSysConfigList(sysConfigQuery);
        Paging<SysConfigVo> paging = new Paging<>(list);
        return paging;
    }

}
